import { computed, nextTick, ref } from "vue";
import { isLabelTag } from "@/views/formgen/components/GenerateForm/FormItemLabel";
import { commonFormat } from "@/views/form/data/table/formatTableColumn";
import { removeHtmlTag } from "@/views/formgen/utils";
import { cloneDeep } from "lodash-es";
import { ElMessageBox } from "element-plus";
import { i18n } from "@/i18n";

export function useSubForm(props: any) {
  const disabled = computed(() => {
    return props.item.disabled;
  });

  const addOrUpdateRef = ref();

  const addOrUpdateVisible = ref(false);
  const isVisible = ref(true);

  const updateIndex = ref(-1);

  const showText = (row: any, key: string, item: any) => {
    let value = row[key];
    if (isLabelTag(key)) {
      value = row[`${key}label`];
    }
    return commonFormat(item.typeId, key, value, { scheme: item }, row);
  };

  const getTableColumnLabel = (option: any) => {
    if (option.config.label) {
      return removeHtmlTag(option.config.label);
    }
    return "";
  };

  const removeDomain = (index: number) => {
    ElMessageBox.confirm(i18n.global.t("formgen.subform.deleteConfirm"), i18n.global.t("common.tip"), {
      confirmButtonText: i18n.global.t("common.confirm"),
      cancelButtonText: i18n.global.t("common.cancel"),
      type: "warning"
    }).then(() => {
      if (index !== -1) {
        props.value.splice(index, 1);
      }
    });
  };

  const updateDomain = (index: number, data: any) => {
    addOrUpdateVisible.value = true;
    updateIndex.value = index;
    nextTick(() => {
      addOrUpdateRef.value.showDialog(cloneDeep(data));
    });
  };

  const copyDomain = (data: any) => {
    if (checkRowCountMax()) {
      return;
    }
    props.value.push(data);
  };

  const addDomain = () => {
    addOrUpdateVisible.value = true;
    updateIndex.value = -1;
    nextTick(() => {
      addOrUpdateRef.value.showDialog();
    });
  };

  const handleFormSubmit = (val: any) => {
    console.log(val);
    if (updateIndex.value != undefined && updateIndex.value != -1) {
      props.value[updateIndex.value] = cloneDeep(val);
    } else {
      props.value.push(cloneDeep(val));
    }
  };

  /**
   * 检查行数是否到达上限
   */
  const checkRowCountMax = (): boolean => {
    if (undefined !== props.item.config.maxRowCount) {
      if (props.value.length >= props.item.config.maxRowCount) {
        return true;
      }
    }
    return false;
  };

  return {
    disabled,
    addOrUpdateRef,
    addOrUpdateVisible,
    isVisible,
    showText,
    getTableColumnLabel,
    removeDomain,
    updateDomain,
    copyDomain,
    addDomain,
    handleFormSubmit,
    checkRowCountMax
  };
}
